<script setup>
import { Lock, User } from '@element-plus/icons-vue'
import { reactive, ref, watch } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { useRouter } from 'vue-router'
import { getUserInfo, userLogin, userRegister } from '@/api/user.js'

const userStore = useUserStore()
const router = useRouter()
const form = ref() //校验使用
const isRegister = ref(false)
// 添加注册的数据对象(绑定在:model="formModel"上)
const formModel = reactive({
  username: '',
  password: '',
  repassword: ''
})
// 添加验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'change' },
    { min: 2, max: 10, message: '用户名长度只能在2-10个字符之间', trigger: 'change' }
  ],// triggery 表示触发时机
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{7,}$/,
      message: '密码必须包含字母和数字，长度为7-16位',
      trigger: 'change'
    }
  ],
  repassword: [
    { required: true, message: '请再次输入密码', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        // 判断两次输入的密码是否一致
        if (value !== formModel.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'change'
    }]
}
// 当用户输入完所有的数据后校验用户输入是否合法
const checkRegister = async () => {
  await form.value.validate()// 校验数据
  const res = await userRegister(formModel.username, formModel.password)
  ElMessage.success('注册成功')
  isRegister.value = false
}
/**
 * 登录
 * @return {Promise<*>}
 */
const checkLogin = async () => {
  await form.value.validate()// 校验数据
  const res = await userLogin(formModel.username, formModel.password)
  console.log(res)
  if (res.status !== 200) {
    return ElMessage.error('用户名或密码错误')
  }
  //TODO 我看你们后端好像并没有校验token,这里res的返回值不需要
  // 存入token在此
  //获取用户信息
  const userInfo = await getUserInfo(res.data.uid)
  const user = {
    id: userInfo.data.id,
    uid: res.data.uid,
    name: res.data.userName,
    avatar: userInfo.data.headshot,
    address: userInfo.data.address,
    phone: userInfo.data.phone,
    age: userInfo.data.age,
    gender: userInfo.data.sex,
    role: res.data.role
  }
  userStore.setUser(user)
  ElMessage.success('登录成功')
  // 登录成功后跳转到首页
  setTimeout(() => {
    router.push('/')
  }, 1000)
}
// 当切换注册和登录时清空表单数据
watch(isRegister, () => {
  formModel.value = {
    username: '',
    password: '',
    repassword: ''
  }
})

</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :offset="3" :span="6" class="form">
      <transition mode="out-in" name="fade">
        <!-- 注册展示 -->
        <el-form v-if="isRegister" ref="form" :model="formModel" :rules="rules" autocomplete="off" size="large">
          <el-form-item>
            <h1>注册</h1>
          </el-form-item>
          <el-form-item prop="username">
            <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="formModel.password" :prefix-icon="Lock" placeholder="请输入密码"
                      type="password"></el-input>
          </el-form-item>
          <el-form-item prop="repassword">
            <el-input v-model="formModel.repassword" :prefix-icon="Lock" placeholder="请输入再次密码"
                      type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button auto-insert-space class="button" color="#39c5bb" @click="checkRegister">
              注册
            </el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link :underline="false" type="info" @click="isRegister = false">
              ← 返回
            </el-link>
          </el-form-item>
        </el-form>


        <!-- 登录注册展示 -->
        <el-form v-else ref="form" :model="formModel" :rules="rules" autocomplete="off" size="large">
          <el-form-item>
            <h1>登录</h1>
          </el-form-item>
          <el-form-item prop="username">
            <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="formModel.password" :prefix-icon="Lock" name="password" placeholder="请输入密码"
                      type="password"></el-input>
          </el-form-item>
          <el-form-item class="flex">
            <div class="flex">
              <el-checkbox>记住我</el-checkbox>
              <el-link :underline="false" type="primary">忘记密码？</el-link>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button auto-insert-space class="button" color="#39c5bb" @click="checkLogin">登录</el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link :underline="false" type="info" @click="isRegister = true">
              注册 →
            </el-link>
          </el-form-item>
        </el-form>
      </transition>

    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: //url('@/static/test.png') no-repeat 60% center / 240px auto,
      url('@/static/test.png') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }


  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    @keyframes fade-leave {

      // 设置离场动画
      0% {
        transform: translateX(0);
      }

      50% {
        transform: translateX(-100px);
      }

      100% {
        transform: translateX(0px);
      }
    }

    @keyframes fade-enter {
      0% {
        transform: translateX(100px);
      }

      33% {
        transform: translateX(-100px);
      }

      66% {
        transform: translateX(50px);
      }

      100% {
        transform: translateX(0px);
      }
    }

    .fade-enter-from {
      opacity: 0;
    }

    .fade-enter-to {
      // 元素入场完毕时状态
      opacity: 1;
    }

    .fade-enter-active {
      // 元素入场时触发
      animation: fade-enter 1s;
      transition: opacity 2s;
    }

    .fade-leave-active {
      // 元素离场时触发
      animation: fade-leave 1s reverse;
      transition: opacity 1s;
    }

    .fade-leave-to {
      // 元素离场完毕时状态
      opacity: 0;
    }

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
      color: #ffffff;
      font-size: 18px;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
